<template>
  <el-dialog v-model="visible" :close-on-click-modal="false" draggable destroy-on-close :width="'50%'">
    <template #header>
      <el-button :icon="Printer" type="primary" @click="print">打印</el-button>
      <el-button :icon="Document" type="primary" @click="toPdf">导出PDF</el-button>
    </template>
    <el-scrollbar height="600px"><div id="preview_content_design"></div></el-scrollbar>
  </el-dialog>
</template>

<script setup name="PrintPreview">
import { Printer, Document } from '@element-plus/icons-vue';
import { ref, nextTick } from 'vue';
import { newHiprintPrintTemplate } from '@/utils/template-helper';
const visible = ref(false);
const templateInstance = ref(null);
const printData = ref({});
const filename = ref('打印预览');
// 显示弹窗方法
function show(templateJson, data = {}, fname = '打印预览') {
  filename.value = fname;
  printData.value = data;
  templateInstance.value = newHiprintPrintTemplate({ template: templateJson });
  visible.value = true;
  nextTick(() => {
    $('#preview_content_design').html(templateInstance.value.getHtml(data));
  });
}

// 打印操作
const print = () => {
  let options = { leftOffset: -1, topOffset: -1 };
  let ext = {
    callback: () => {},
    styleHandler: () => {
      let css = '<link href="/print-lock.css" media="print" rel="stylesheet">';
      return css;
    }
  };
  templateInstance.value.print(printData.value, options, ext);
};

function toPdf() {
  templateInstance.value.toPdf(printData.value, filename.value);
}

defineExpose({
  show
});
</script>
